package com.guqj.zookeeper.lock;

public class LockNode implements Comparable<LockNode> {

	private String id;
	private String prefix;
	private int sequence = -1;

	public LockNode(String id) {
		if (id == null) {
			throw new NullPointerException("id cannot be null");
		}
		this.id = id;
		this.prefix = id;
		int idx = id.lastIndexOf('-');
		if (idx >= 0) {
			this.prefix = id.substring(0, idx);
			try {
				this.sequence = Integer.parseInt(id.substring(idx + 1));
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (ArrayIndexOutOfBoundsException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public int compareTo(LockNode that) {
		int s1 = this.sequence;
		int s2 = that.sequence;
		if (s1 == -1 && s2 == -1) {
			return this.id.compareTo(that.id);
		}
		if (s1 == -1) {
			return -1;
		} else if (s2 == -1) {
			return 1;
		} else {
			return s1 - s2;
		}
	}

	public String getId() {
		return id;
	}

}
